import { ArticleModel } from '~/server/models/article.model';

export default defineEventHandler(async (event) => {
	const query = getQuery(event);
	const { id } = query;
	if (!id) {
		return { code: 0, message: '缺少文章ID' };
	}
	try {
		const article = await ArticleModel.findById(id).populate('categoryId', 'name').lean();
		if (!article) {
			return { code: 0, message: '未找到对应文章' };
		}
		let categoryName = '';
		if (
			article.categoryId &&
			typeof article.categoryId === 'object' &&
			'name' in article.categoryId
		) {
			categoryName = (article.categoryId as any).name;
		}
		return { code: 1, data: { ...article, categoryName } };
	} catch (e: any) {
		return { code: 0, message: e.message };
	}
});
